<script lang="ts" setup>
import type { LoginParams } from '@vben/common-ui';

import { onMounted, ref } from 'vue';

import { AuthenticationLogin } from '@vben/common-ui';

import { capCheck, capJson } from '#/api';
import { useAuthStore } from '#/store';

defineOptions({ name: 'Login' });

const vCodeSrc = ref('');
const vCap = ref('');
const authStore = useAuthStore();

const getSumId = () => {
  if (vCap.value) {
    return vCap.value;
  }
  const cap = localStorage.getItem('_cap');
  cap && (vCap.value = cap);
  return cap || '';
};

const setSumId = (sumId: string) => {
  vCap.value = sumId;
  localStorage.setItem('_cap', sumId);
};

const reCode = async () => {
  const sumId = getSumId();
  const result = await capJson({ sumid: sumId });
  if (result) {
    sumId !== result._cap && setSumId(result._cap);
    vCodeSrc.value = `data:image/png;base64,${result.image}`;
  }
};

const authLogin = async (params: LoginParams) => {
  const result = await capCheck({
    sumid: getSumId(),
    vcode: params.token,
  });
  if (result.retCode !== 0) {
    reCode();
    return;
  }
  params.token = result.xtoken;
  try {
    await authStore.authLogin(params);
  } catch {
    await reCode();
  }
};
// 加载数据资料信息
onMounted(async () => {
  await reCode();
});
</script>

<template>
  <AuthenticationLogin
    :loading="authStore.loginLoading"
    :vcode="vCodeSrc"
    @refresh-code="reCode"
    @submit="authLogin"
  />
</template>
